package com.rp.system.controller;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.common.vo.PageData;
import com.rp.controller.RpController;
import com.rp.system.po.RpMessage;
import com.rp.system.po.User;
import com.rp.system.service.RpMessageService;

@Controller
@RequestMapping("/rp/system/msg/")
public class RpMessageController extends RpController {

	@Autowired
	private RpMessageService msgService;
	
	@RequestMapping("showMsgGrid")
	public ModelAndView showMsgGrid(String moduleAlias){
		List<Record> rs = 
				Db.use("rpDb").find("select * from rp_system_buttons where moduleAlias = ?", moduleAlias); 
		model.put("buttons", JSONArray.fromObject(RpUtil.jfinalListToList(rs)).toString());
		
		return forward("rp/system/msg/msgGrid.jsp");
	}
	
	/**
	 * 获取当前登陆用户有多少条未读消息
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getInboxForMyMsg")
	public String getInboxForMyMsg(){
		Long count = Db.use("rpDb").queryLong("select count(*) from RP_SYSTEM_USER_MESSAGES um where um.userId = '"
				+User.getCurrentUser().getId()+"' and um.markRead = '0'");
		
		return count.toString();
	}
	
	/**
	 * 获取收件箱数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping("inboxData")
	public PageData inboxData(){
		
		String currentUserId = User.getCurrentUser().getId();
		
		Page<Record> jfinalPage = Db.use("rpDb")
				.paginate(pageParam.getPageNumber(), pageParam.getPageSize(), "select m.*,um.markRead,um.id as umId", 
						"from rp_system_messages m left join rp_system_user_messages um on m.id = um.messageId where um.userId = '"+currentUserId+"'" + pageParam.getOrderBy("m"));
		
		return new PageData(jfinalPage.getTotalRow(), RpUtil.jfinalPageToList(jfinalPage));
		
	}
	
	/**
	 * 获取发件箱数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping("outboxData")
	public PageData outboxData(){
		
		String currentUserId = User.getCurrentUser().getId();
		
		Page<Record> jfinalPage = Db.use("rpDb")
				.paginate(pageParam.getPageNumber(), pageParam.getPageSize(), 
						"select t1.id,t1.createDate,t1.content,t1.creatorName,t1.title,t1.receiver, "
						+ "sum(case markread when '0' then 1 else 0 end) as readFalse, sum(case markread when '1' then 1 else 0 end)as readTrue", 
						//"from rp_system_messages m where m.creatorId = ?" + pageParam.getOrderBy("m"), currentUserId);
						"from rp_system_messages t1 left join rp_system_user_messages t2 on t1.id = t2.messageid "
						+ "where t1.creatorId = ? group by t1.id,t1.createDate,t1.content,t1.creatorName,t1.creatorId,t1.title,t1.receiver "+pageParam.getOrderBy("t1"), currentUserId);
		
		return new PageData(jfinalPage.getTotalRow(), RpUtil.jfinalPageToList(jfinalPage));
		
	}
	
	/**
	 * 获取接收人状态（已读或未读）列表
	 * @param messageId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getRecipientStatus")
	public List<Map<String, Object>> getRecipientStatus(String messageId){
		
		List<Record> rs = Db.use("rpDb").find("select um.*,u.realname from rp_system_user_messages as um left join rp_system_users as u on um.userId = u.id where um.messageId = ?" + pageParam.getOrderBy("um"), messageId);
		
		return RpUtil.jfinalListToList(rs);
	}
	
	@ResponseBody
	@RequestMapping("setMarkRead")
	public String setMarkRead(String json){
		List<Map<String, Object>> msgs = JsonUtil.jsonToList(json);
		for (Map<String, Object> map : msgs) {
			String sql = "update RP_SYSTEM_USER_MESSAGES set markRead = '1', updateDate = '"+RpUtil.getCurrentDatetime()+"' where id = ?";
			Db.use("rpDb").update(sql, (String) map.get("umId"));
		}
		return SUCCESS;
	}
	
	
	@ResponseBody
	@RequestMapping("sendMessage")
	public String sendMessage(String userIds, String title, String content, String receiver){
		
		RpMessage rm = new RpMessage();
		rm.setCreatorId(User.getCurrentUser().getId());
		rm.setCreatorName(User.getCurrentUser().getRealname());
		rm.setTitle(title);
		rm.setContent(content);
		rm.setReceiver(receiver);
		
		try {
			msgService.sendMessage(userIds, rm);
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_MSG + e.getMessage();
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteInboxMessages")
	public String deleteInboxMessages(String json){
		List<Map<String, Object>> msgs = JsonUtil.jsonToList(json);
		for (Map<String, Object> map : msgs) {
			String umId = (String) map.get("umId");
			Db.use("rpDb").deleteById("RP_SYSTEM_USER_MESSAGES", umId);
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteOutboxMessages")
	public String deleteOutboxMessages(String json){
		List<Map<String, Object>> msgs = JsonUtil.jsonToList(json);
		for (Map<String, Object> map : msgs) {
			msgService.deleteMessage((String) map.get("id"));
		}
		return SUCCESS;
	}
	
	
}
